<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>

</head>
<body>


<div id="app">

    编号: <input type="text" v-model="good.id">
    名称: <input type="text" v-model="good.goodsName">
    价格: <input type="text" v-model="good.price">
    数量: <input type="text" v-model="good.count">
    <button type="submit" @click="addGood">确认</button>


    <table border="1" width="50%">
        <caption v-text="msg"></caption>
        <thead>
        <tr>
            <th>编号</th>
            <th>商品名称</th>
            <th>商品单价</th>
            <th>购买数量</th>
            <th>小计</th>
        </tr>
        </thead>
        <tbody>
        <tr v-for="good, index in lists" :key="good.id">
            <td>{{good.id}}</td>
            <td>{{good.goodsName}}</td>
            <td>{{good.price}}</td>
            <td ><input type="button" value="+ " @click="add(index)"> {{  good.count  }}  <input type="button" value="  -" @click="sub(index)"></td>
            <td >{{(good.price * good.count).toFixed(2)}}</td>
        </tr>
        </tbody>
    </table>
    总计：{{totalAll()}}
</div>

</body>
</html>

<script src="./vue.js"></script>

<script>

    var app = new Vue({
        el: "#app",
        data: {
            msg: "我的购物车",
            good: {},
            lists: [{id: 1, goodsName: "iphone12", price: 10000, count: 1},
                {id: 2, goodsName: "huaweiP50", price: 11000, count: 1}],
        },
        methods: {
            add(index) {
                var count = this.lists[index].count;
                count = count + 1;
                this.lists[index].count = count;
                // this.totalAll();
            },

            sub(index){
                if (this.lists[index].count > 0){
                    this.lists[index].count--;
                }
                // this.totalAll();
            },

            totalAll(){
                var totalAll = 0;
                for(var i = 0; i < this.lists.length; i++){
                    totalAll += this.lists[i].price * this.lists[i].count;
                }
                return totalAll;
            },

            addGood(){
                if (this.good.id != null && this.good.goodsName != null && this.good.price != null && this.good.count != null){
                    this.lists.push(this.good);
                }

            }
        }



    })


</script>